package com.haruhi.bot.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.UUID;

@Slf4j
public class CommonUtil {

    public static String getMd5(byte[] types){
        return DigestUtils.md5DigestAsHex(types);
    }
    public static String getMd5(File file){
        InputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            return DigestUtils.md5DigestAsHex(fileInputStream);
        } catch (Exception e) {
            log.error("获取md5异常:{}",e.getMessage());
            e.printStackTrace();
            return "";
        }finally {
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public static String getNewFileName(String originalFilename){
        String fileSuffix = getFileSuffix(originalFilename);
        if(ParamUtil.isEmpty(fileSuffix)){
            fileSuffix = "jpg";
        }
        return getUUID() + "." + fileSuffix;
    }

    public static String getUUID(){
        return UUID.randomUUID().toString().replace("-","");
    }

    public static String getFileSuffix(String originalFilename){
        try {
            String[] split = originalFilename.split("\\.");
            return split[split.length - 1];
        }catch (Exception e){
            return "";
        }
    }

    public static void deleteFile(String path){
        if(!ParamUtil.isEmpty(path)){
            deleteFile(new File(path));
        }
    }
    public static void deleteFile(File file){
        if(file != null && file.exists() || file.isFile()){
            file.delete();
        }
    }
}
